package com.xsd.xsdhouduan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xsd.xsdhouduan.common.Result;
import com.xsd.xsdhouduan.entity.Task;
import com.xsd.xsdhouduan.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 任务控制器
 */
@RestController
@RequestMapping("/api/tasks")
@CrossOrigin
public class TaskController {
    
    @Autowired
    private TaskService taskService;
    
    /**
     * 获取所有任务
     */
    @GetMapping
    public Result<List<Task>> getAllTasks() {
        List<Task> tasks = taskService.getAllTasksWithDetails();
        return Result.success(tasks);
    }
    
    /**
     * 根据学校获取任务
     */
    @GetMapping("/school/{schoolId}")
    public Result<List<Task>> getTasksBySchool(@PathVariable Long schoolId) {
        List<Task> tasks = taskService.getBySchoolId(schoolId);
        return Result.success(tasks);
    }
    
    /**
     * 根据状态获取任务
     */
    @GetMapping("/status/{status}")
    public Result<List<Task>> getTasksByStatus(@PathVariable Integer status) {
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Task::getStatus, status);
        List<Task> tasks = taskService.list(wrapper);
        // 填充任务详情
        tasks = tasks.stream().map(task -> {
            // 这里需要调用TaskService的填充方法，暂时先返回原任务
            return task;
        }).collect(java.util.stream.Collectors.toList());
        return Result.success(tasks);
    }
    
    /**
     * 搜索任务
     */
    @GetMapping("/search")
    public Result<List<Task>> searchTasks(@RequestParam(required = false) String keyword,
                                          @RequestParam(required = false) Long schoolId,
                                          @RequestParam(required = false) Integer status) {
        LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<>();
        
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.and(w -> w.like(Task::getTitle, keyword)
                    .or()
                    .like(Task::getDescription, keyword));
        }
        
        if (schoolId != null) {
            wrapper.eq(Task::getSchoolId, schoolId);
        }
        
        if (status != null) {
            wrapper.eq(Task::getStatus, status);
        }
        
        wrapper.orderByDesc(Task::getCreateTime);
        
        List<Task> tasks = taskService.list(wrapper);
        return Result.success(tasks);
    }
    
    /**
     * 获取任务详情
     */
    @GetMapping("/{taskId}")
    public Result<Task> getTaskById(@PathVariable Long taskId) {
        Task task = taskService.getById(taskId);
        if (task != null) {
            return Result.success(task);
        }
        return Result.error("任务不存在");
    }
}
